/**
 * 易驰护运 - Home
 * http://menger.me
 * @大梦
 */

'use strict';

import React from 'react'
import {
    StyleSheet, 
    Text, 
    ScrollView, 
    TouchableOpacity, 
    TextInput, 
    ImageBackground, 
    View, 
    Keyboard, 
    PermissionsAndroid,
} from 'react-native'
import {
    IconFont,
    ListView,
    VerticalLine,
    HorizontalLine,
    BannerComponent,
    HotNewsComponent,
    HomeResourceItem,
    ListHeaderLoading,
} from '../../components'
import {HomeStyle} from '../../style'
import {inject, observer} from 'mobx-react'
import ViewShot, { captureScreen } from "react-native-view-shot"
import CameraRoll from '@react-native-community/cameraroll'

@inject('loginStore')
@observer
export default class Home extends React.Component {
    constructor(props) {
        super(props);
        let {loginStore} = this.props;
        this.state = {
            cityData: loginStore.location,
            news_data: [],
            banner_index: [],
            menuSource: [],
            dataSources: [],
            news_message: '',
            unread: '',
        };
        this.page = 1;
        this.limit = 10;
    }

    // 增加CallBack的跳转方法
    _onPressToNavigate = (pageTitle, component, params) => {
        RouterHelper.navigate(pageTitle, component, {
            ...params,
        });
    };

    componentDidMount() {
        // 请求地理位置信息
        this._getCurrentPosition();
        // 检查身份状态
        this.checkState();
        // 检查车辆状态
        this.checkValidity();
        // 未读信息提醒
        this.readMessage();
        // 请求最新公告
        this.requestData();
        // 请求平台数据
        this._requestHotNews();
        // 请求轮播图信息
        this._requestBannerResources();
        // 请求菜单数据
        this._requestMenuSources();
        // 请求首页信息
        this._requestDataSources();
    }

    // 请求地理位置信息
    _getCurrentPosition = async () => {
        let {loginStore} = this.props;
        let {getCurrentPosition} = loginStore;
        getCurrentPosition && getCurrentPosition();
    };

    // 检查身份状态
    checkState = async () => {
        let {loginStore} = this.props;
        let {userInfo} = loginStore;
        userInfo.id && userInfo.is_pass != 1 && this._onPressApprove()
    }

    // 认证
    _onPressApprove = () => {
        let params = {
            title: '温馨提醒',
            detail: '您需要先通过认证才能接单哦',
            actions: [
                {title: '再看看'},
                {
                    title: '公司认证',
                    titleStyle: {color: Predefine.themeColor},
                    onPress: () => RouterHelper.navigate('', 'Approve')
                },
            ]
        };
        AlertManager.show(params);
    }

    // 检查车辆状态
    checkValidity = async () => {
        let url = ServicesApi.INDEX_CHECK_VALIDITY;
        let data = {};
        const result = await Services.post(url, data);
    }

    // 未读信息提醒
    readMessage = async () => {
        let url = ServicesApi.INDEX_UNREAD;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                unread: result.data,
            })
        }
    }

    // 请求最新公告
    requestData = async () => {
        let url = ServicesApi.INDEX_NOTICE;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                news_message: result.data.content,
            });
        }
    }

    // 请求平台数据
    _requestHotNews = async () => {
        let url = ServicesApi.INDEX_DATE;
        let data = {};
        let result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                news_data: result.data,
            });
        }
    };

    // 请求轮播图信息
    _requestBannerResources = async () => {
        let url = ServicesApi.INDEX_BANNER_LIST;
        let data = {
            type: 2, // 1货主 2承运商
        };
        let result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({banner_index: result.data});
        }
    };

    // 请求菜单数据
    _requestMenuSources = async () => {
        let url = ServicesApi.INDEX_INDEX_MENU;
        let data = {  };
        let result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({ menuSource: result.data })
        }
    }

    // 请求首页信息
    _requestDataSources = async () => {
        let {dataSources, cityData} = this.state;
        let url = ServicesApi.GOODS_GOODS_LIST;
        let data = {
            from_province: cityData.province.name,
            from_city: cityData.city.name,
            from_district: cityData.area.name,
            page: this.page,
            limit: this.limit,
        };
        try {
            const result = await Services.post(url, data);
            let dataSourcesTemp = dataSources.slice();
            let dataList = [];
            if (result.code === StatusCode.SUCCESS_CODE) {
                dataList = result.data.dataList;
                if (parseInt(data.page) === 1) {
                    dataSourcesTemp = dataList
                } else {
                    if (dataList.length !== 0) {
                        dataSourcesTemp = dataSourcesTemp.concat(dataList);
                    }
                }
            }
            this.setState({
                dataSources: dataSourcesTemp,
                loading: false
            });
            this._onStopLoading(dataList.length < this.limit);
        } catch (error) {
            this._onStopLoading(true);
        }
    };

    _onStopLoading = (status) => {
        this.setState({ready: true});
        this._listRef && this._listRef.stopRefresh();
        this._listRef && this._listRef.stopEndReached({allLoad: status});
    };

    _captureRef = (v) => {
        this._listRef = v
    };

    _keyExtractor = (item, index) => {
        return `item_${index}`
    };

    _onRefresh = () => {
        this.page = 1;
        this.readMessage();
        this.requestData();
        this._requestHotNews();
        this._requestBannerResources();
        this._requestMenuSources();
        this._requestDataSources();
    };

    _onEndReached = () => {
        this.page++;
        this._requestDataSources()
    };

    _onPressItem = async (item) => {
        this._onPressToNavigate(item.title, 'SupplyDetail', {item});
    };

    _renderListItem = ({item}) => {
        return (
            <HomeResourceItem
                item={item}
                onPress={() => this._onPressItem(item)}
                {...this.props}
            />
        )
    };

    // 跳转查看协议（用户协议）
    checkArticle = async (type) => {
        let url = ServicesApi.ARTICLE_ARTICLE_LIST;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            RouterHelper.navigate('', 'Agreement', {
                agreementTitle: type === 'yong_hu' ? result.data[0].title : result.data[3].title,
                agreementUrl: type === 'yong_hu' ? result.data[0].url : result.data[3].url
            })
        }
    }

    // 未开放功能
    onPressWindow = () => {
        AlertManager.show({
            title: '温馨提示',
            detail: '暂未开放，敬请期待',
            onPress: () => {
                AlertManager.hide();
            },
            actions: [
                {title: '确定'},
            ],
        });
    }

    // 地区选择
    showActionAreaPicker = () => {
        let {cityData} = this.state;
        let params = {
            defaultData: cityData,
            onCallBack: (selectedData) => {
                this.setState({
                    cityData: selectedData
                }, () => this._onRefresh());
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showCityTree(params);
    };

    _renderNavigationContent = (menuSource) => {
        if (!menuSource || menuSource.length < 1) return null;
        let content = menuSource.map((item, index) => {
            if (item.display == 1) {
                return (
                    <Button
                        key={index}
                        icon={{uri: item.img}}
                        title={item.title}
                        style={styles.navigateItemStyle}
                        iconStyle={styles.navigateIconStyle}
                        iconPosition={Constants.POSITION_TOP}
                        titleStyle={styles.navigateTitleStyle}
                        onPress={() => {
                            index == 0 && RouterHelper.navigate('', 'Calculation'),
                            index == 4 && this.checkArticle('yong_hu'),
                            index == 5 && this.checkArticle('yin_si')
                        }}
                    />
                );
            }
        });
        return content;
    }

    _renderListHeaderComponent = (state) => {
        let { banner_index, menuSource, news_data, news_message, cityData } = state;
        return (
            <View styles={styles.listHeaderContent}>
                <BannerComponent data={banner_index}/>
                <View style={styles.newsContainer}>
                    <ImageView
                        resizeMode={'contain'}
                        style={styles.noticeIconStyle}
                        source={Images.icon_notice_title}
                    />
                    <Text style={styles.noticeContext} numberOfLines={1}>{news_message || '暂无公告'}</Text>
                </View>
                <View style={[styles.listHeaderItemContent]}>
                    <View style={[Predefine.RCB]}>
                        <View style={[Predefine.RCB, styles.todatDataItemView]}>
                            <View style={[Predefine.CCC, styles.todatDataItemContent]}>
                                <Text style={styles.todatDataItemValue}>{news_data.today_new_goods_total}吨</Text>
                                <Text style={styles.todatDataItemTitle}>今日新增货源</Text>
                            </View>
                        </View>
                        <View style={[Predefine.RCB, styles.todatDataItemView]}>
                            <VerticalLine style={styles.verticalSeparatorStyle}/>
                            <View style={[Predefine.CCC, styles.todatDataItemContent]}>
                                <Text style={styles.todatDataItemValue}>{news_data.today_new_order_total}单</Text>
                                <Text style={styles.todatDataItemTitle}>今日新增订单</Text>
                            </View>
                        </View>
                    </View>
                </View>
                <View style={[styles.listHeaderItemContent]}>
                    <View style={[Predefine.RCB]}>
                        <View style={[Predefine.RCB, styles.todatDataItemView]}>
                            <View style={[Predefine.CCC, styles.todatDataItemContent]}>
                                <Text style={styles.todatDataItemValue}>{news_data.goods_total}吨</Text>
                                <Text style={styles.todatDataItemTitle}>平台资源总数</Text>
                            </View>
                        </View>
                        <View style={[Predefine.RCB, styles.todatDataItemView]}>
                            <VerticalLine style={styles.verticalSeparatorStyle}/>
                            <View style={[Predefine.CCC, styles.todatDataItemContent]}>
                                <Text style={styles.todatDataItemValue}>{news_data.order_total}单</Text>
                                <Text style={styles.todatDataItemTitle}>平台订单总数</Text>
                            </View>
                        </View>
                        <View style={[Predefine.RCB, styles.todatDataItemView]}>
                            <VerticalLine style={styles.verticalSeparatorStyle}/>
                            <View style={[Predefine.CCC, styles.todatDataItemContent]}>
                                <Text style={styles.todatDataItemValue}>{news_data.order_cost_total}元</Text>
                                <Text style={styles.todatDataItemTitle}>平台运费总数</Text>
                            </View>
                        </View>
                    </View>
                </View>
                <View style={[Predefine.RCB, styles.listHeaderItemContent]}>
                    {this._renderNavigationContent(menuSource)}
                </View>
                <View style={[Predefine.RCS, styles.listHeaderItemContent]}>
                    <View style={Predefine.RCS}>
                        <VerticalLine style={styles.itemContentIconStyle}/>
                        <Text style={styles.itemContentTitleStyle}>{cityData.city.name}资源</Text>
                    </View>
                    <Button
                        style={styles.supplyBtn}
                        title={'更多货源'}
                        titleStyle={styles.supplyBtnTitle}
                        resizeMode={'cover'}
                        backgroundImage={Images.img_btn_bg1}
                        onPress={() => RouterHelper.navigate('', 'Supply')}
                    />
                </View>
            </View>
        );
    };

    _renderLeftAction = (cityData) => {
        return (
            <View style={[Predefine.RCS, styles.navBarLeftAction]}>
                <ImageView
                    source={Images.img_logo_index}
                    style={styles.indexLogoStyle}
                />
                <Button
                    title={cityData.city.name}
                    style={styles.navBtnItemStyle}
                    iconPosition={Constants.POSITION_RIGHT}
                    icon={<IconFont.AntDesign name={'caretdown'} style={styles.navBtnIconStyle}/>}
                    titleStyle={styles.navBtnTitleStyle}
                    onPress={() => this.showActionAreaPicker()}
                />
            </View>
        );
    };

    _saveToCameraRoll = async (uri) => {
        if (__ANDROID__) {
            let perRes = await PermissionsAndroid.request('android.permission.WRITE_EXTERNAL_STORAGE', null);
        }
        console.log("Image saved to", uri)
        const saveRes = await CameraRoll.saveToCameraRoll(uri, 'photo');
        if (saveRes) {
            ToastManager.message('保存成功');
        }
    };

    _renderCaptureScreenDemo = () => {
        return (
            <View style={styles.viewStyle}>
                <Button
                    title={'截单屏'}
                    style={{margin: 15}}
                    onPress={() => {
                        captureScreen({
                              format: "jpg",
                              quality: 0.8
                            }).then((uri) => {
                                this._saveToCameraRoll(uri);
                            },
                              error => console.error("Oops, snapshot failed", error)
                            );
                    }}
                />
                <Button
                    title={'截长屏'}
                    style={{margin: 15}}
                    onPress={() => {
                        this.viewShotRef.capture().then(uri => {
                          this._saveToCameraRoll(uri);
                        });
                    }}
                />
                <ScrollView
                    style={{flex: 1}}
                    keyboardShouldPersistTaps={'handled'}
                >
                    <ViewShot
                        ref={ref => this.viewShotRef = ref}
                        options={{ format: "jpg", quality: 0.9}}
                        style={{flex: 1, backgroundColor: '#fff'}}
                    >
                        <View style={[Predefine.CCA, {height: 1000, backgroundColor: '#f60'}]}>
                            <Text style={{color: '#fff', fontSize: 30}}>头</Text>
                            <Text style={{color: '#fff', fontSize: 30}}>底</Text>
                        </View>
                    </ViewShot>
                </ScrollView>
            </View>
        );
    };


    render() {
        let { dataSources, cityData, unread } = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar
                    title={null}
                    style={[styles.navigationBarStyle]}
                    renderLeftAction={() => this._renderLeftAction(cityData)}
                    renderRightAction={[
                        {
                            title: <IconFont.AntDesign name={'search1'} size={20} color={'#fff'}/>,
                            onPress: () => this._onPressToNavigate('', 'Search')
                        },
                        {
                            title: <IconFont.AntDesign name={'message1'} size={18} color={'#fff'}/>,
                            onPress: () => this._onPressToNavigate('', 'SystemMessage', {
                                onCallBack: () => this.readMessage()
                            })
                        }
                    ]}
                />
                { unread != 0 && <View style={styles.unread}/> }
                <View style={styles.content}>
                    <ListView
                        data={dataSources}
                        exData={this.state}
                        ref={this._captureRef}
                        style={styles.ListView}
                        onRefresh={this._onRefresh}
                        renderItem={this._renderListItem}
                        keyExtractor={this._keyExtractor}
                        onEndReached={this._onEndReached}
                        ListHeaderComponent={() => this._renderListHeaderComponent(this.state)}
                    />
                </View>
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    ...HomeStyle,

    unread: {
        position: 'absolute',
        right: 10,
        top: 30,
        height: 8,
        width: 8,
        borderRadius: 4,
        backgroundColor: '#FF0000',
    },
    supplyBtn: {
        backgroundColor: DominantColor,
        height: 30,
        width: 100,
        paddingVertical: 0,
        paddingHorizontal: 0,
    },
    newsContainer: {
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        backgroundColor: '#fff',
    },
    noticeIconStyle: {
        width: 60,
        height: 25,
    },
    noticeContext: {
        flex: 1,
        fontSize: 15,
        marginLeft: 6,
    },
    textArea1: {
        maxHeight: 400,
        paddingHorizontal: 15,
        color: '#333',
    },
});